package io.xxx.xbutler.core.get;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import io.xxx.xbutler.client.ProductClient;
import io.xxx.xbutler.client.PromotionClient;
import io.xxx.xbutler.domain.Jigsaw;
import io.xxx.xbutler.domain.Product;
import io.xxx.xbutler.domain.SensitiveWord;
import io.xxx.xbutler.domain.Store;
import io.xxx.xbutler.domain.task.ContentType;
import io.xxx.xbutler.domain.task.MessageType;
import io.xxx.xbutler.domain.task.PushContext;
import io.xxx.xbutler.domain.task.TaskItem;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <pre>
 * {
 *     "text": "",
 *     "venueCode": "",
 *     "products": [
 *         {
 *             "sn": 1,
 *             "skuSn": "",
 *             "spuSn": "",
 *             "name": "",
 *             "price": ""
 *         },
 *         {
 *             "sn": 2,
 *             "skuSn": "",
 *             "spuSn": "",
 *             "name": "",
 *             "price": ""
 *         }
 *     ]
 * }
 *
 * 和
 *
 * {
 *     "title": "",
 *     "thumbUrl": "",
 *     "pagePath": "",
 *     "spuSn": "",
 *     "skuSn": "",
 *     "venueCode": "",
 *     "venue": {
 *         "code": "",
 *         “artwork”: "",   // 底图
 *         "products": [
 *             {
 *                 "sn": 1,
 *                 "skuSn": "",
 *                 "spuSn": "",
 *                 "name": "",
 *                 "price": ""
 *             },
 *             {
 *                 "sn": 2,
 *                 "skuSn": "",
 *                 "spuSn": "",
 *                 "name": "",
 *                 "price": ""
 *             }
 *         ],
 *         "theme": "蔬菜有优惠，比超市都便宜",
 *         "templateId": 123,
 *         "templateName": "双商品会场模板",
 *         "title": "蔬菜专卖会场",
 *         "generateCopywriter": true,
 *         "productCopywriter": "xxxxxxxx",
 *         "sensitiveWords": [
 *             {
 *                 "source": "辣椒",
 *                 "target": "辣jiao"
 *             },
 *             {
 *                 "source": "辣椒",
 *                 "target": "辣jiao"
 *             }
 *         ]
 *     }
 * }
 * </pre>
 */
@Slf4j
@Component
public class ProductVenueGetter implements ContentGetter {

    @Resource
    private ProductClient productClient;

    @Resource
    private PromotionClient promotionClient;

    @Value("${venue.copywriter.product.size:15}")
    private Integer copywriterProductSize;

    @Override
    public boolean beforeCheck() {
        return false;
    }

    @Override
    public void replaceContent(PushContext context) {
        LocalDateTime now = LocalDateTime.now();
        Store store = context.getStore() == null ? context.getCutomStore() : context.getStore();

        List<TaskItem> taskItems = context.getTaskItems();
        Map<String, TaskItem> textItemMap = taskItems.stream()
                .filter(it -> it.getMessageType() == MessageType.TEXT || it.getContentType() == ContentType.PRODUCT_VENUE)
                .collect(Collectors.toMap(it -> it.getContent().getString("venueCode"), it -> it));

        for (TaskItem taskItem : taskItems) {
            if (!taskItem.assign(MessageType.MINI_PROGRAM, ContentType.PRODUCT_VENUE) || store == null) {
                continue;
            }
            Long storeId = store.getId();

            JSONObject content = taskItem.getContent();
            String venueCode = content.getString("venueCode");
            JSONObject venue = content.getJSONObject("venue");  // venue root
            List<Product> products = venue.getJSONArray("products")
                    .stream()
                    .map(it -> {
                        JSONObject object = JSONObject.from(it);
                        String skuSn = object.getString("skuSn");
                        return productClient.getSaleProduct(storeId, skuSn, now);
                    })
                    .toList();

            Jigsaw jigsaw = promotionClient.getVenueJigsaw(storeId, venueCode);
            if (jigsaw == null) {
                log.warn("查询会场信息为空[taskId:{}, storeId:{}, storeCode:{}, venueCode:{}]",
                        taskItem.getTaskId(), storeId, store.getCode(), venueCode);
            } else {
                content.put("thumbUrl", jigsaw.getThumbUrl());
                taskItem.setContent(content);
            }

            Boolean generateCopywriter = venue.getBoolean("generateCopywriter");
            if (generateCopywriter != null && generateCopywriter) {
                TaskItem textItem = textItemMap.get(venueCode);
                String text = buildProductCopywriter(venue.getString("theme"), products, venue.getJSONArray("sensitiveWords"));
                JSONObject textContent = new JSONObject() {{
                    put("text", text);
                }};
                textItem.setContent(textContent);
            }
        }
    }

    private String buildProductCopywriter(String theme, List<Product> products, JSONArray array) {
        List<SensitiveWord> sensitiveWords = array.toList(SensitiveWord.class);
        StringBuilder builder = new StringBuilder(theme);
        for (int i = 0; i < copywriterProductSize; i++) {
            Product product = products.get(i);
            builder.append(i + 1).append(". ")
                    .append(product.getSpecification()).append(" | ")
                    .append(product.getName()).append("：").append(product.getPrice())
                    .append("\n");
        }
        builder.append("↓点击购买");
        String copywriter = builder.toString();
        for (SensitiveWord sensitiveWord : sensitiveWords) {
            copywriter = copywriter.replaceAll(sensitiveWord.getSource(), sensitiveWord.getTarget());
        }
        return copywriter;
    }
}
